package com.example.fanyi.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.fanyi.data.TranslationRecord
import com.example.fanyi.data.TranslationRepository
import com.example.fanyi.data.TranslationResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class TranslationViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = TranslationRepository(application)

    private val _sourceText = MutableStateFlow("")
    val sourceText: StateFlow<String> = _sourceText.asStateFlow()

    private val _translatedText = MutableStateFlow("")
    val translatedText: StateFlow<String> = _translatedText.asStateFlow()

    private val _isChineseToUyghur = MutableStateFlow(true)
    val isChineseToUyghur: StateFlow<Boolean> = _isChineseToUyghur.asStateFlow()

    private val _isTranslating = MutableStateFlow(false)
    val isTranslating: StateFlow<Boolean> = _isTranslating.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

    private val _records = MutableStateFlow<List<TranslationRecord>>(emptyList())
    val records: StateFlow<List<TranslationRecord>> = _records.asStateFlow()

    private val _selectedRecords = MutableStateFlow<Set<TranslationRecord>>(emptySet())
    val selectedRecords: StateFlow<Set<TranslationRecord>> = _selectedRecords.asStateFlow()

    init {
        viewModelScope.launch {
            repository.getAllRecords().collect { records ->
                _records.value = records
            }
        }
    }

    fun updateSourceText(text: String) {
        _sourceText.value = text
        if (text.isEmpty()) {
            _translatedText.value = ""
            _errorMessage.value = null
        }
    }

    fun toggleTranslationDirection() {
        _isChineseToUyghur.value = !_isChineseToUyghur.value
        // 清空翻译结果
        _translatedText.value = ""
        _errorMessage.value = null
    }

    fun translate() {
        val text = _sourceText.value.trim()
        if (text.isEmpty()) {
            _errorMessage.value = "请输入要翻译的文本"
            return
        }

        viewModelScope.launch {
            _isTranslating.value = true
            _errorMessage.value = null

            try {
                when (val result = repository.translate(text, _isChineseToUyghur.value)) {
                    is TranslationResult.Success -> {
                        _translatedText.value = result.translatedText
                        _errorMessage.value = null
                        // 保存翻译记录
                        val record = TranslationRecord(
                            sourceText = text,
                            translatedText = result.translatedText,
                            isChineseToUyghur = _isChineseToUyghur.value,
                            timestamp = System.currentTimeMillis()
                        )
                        repository.insertRecord(record)
                    }
                    is TranslationResult.Error -> {
                        _translatedText.value = ""
                        _errorMessage.value = when (result.code) {
                            108 -> "应用ID或密钥无效"
                            111 -> "翻译服务不可用"
                            202 -> "翻译文本过长或包含不支持的字符"
                            401 -> "请求参数有误"
                            411 -> "访问频率受限"
                            else -> result.message ?: "翻译失败 (错误码: ${result.code})"
                        }
                    }
                }
            } catch (e: Exception) {
                _translatedText.value = ""
                _errorMessage.value = "翻译失败: ${e.message}"
            } finally {
                _isTranslating.value = false
            }
        }
    }

    fun toggleRecordSelection(record: TranslationRecord) {
        _selectedRecords.value = _selectedRecords.value.toMutableSet().apply {
            if (contains(record)) remove(record) else add(record)
        }
    }

    fun deleteSelectedRecords() {
        viewModelScope.launch {
            repository.deleteRecords(_selectedRecords.value)
            _selectedRecords.value = emptySet()
        }
    }

    fun clearSelectedRecords() {
        _selectedRecords.value = emptySet()
    }
} 